package com.future.taskdemo.k8s;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @Author chendongwei
 * Date 2022/5/24 9:28
 * @Descrintion http请求
 */
public class RestTemplate {

    static Logger log = LoggerFactory.getLogger(RestTemplate.class);

    private static org.springframework.web.client.RestTemplate restTemplate;

    static {
        restTemplate = new org.springframework.web.client.RestTemplate();
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
    }

    /**
     * @Author chendongwei
     * Date 2022/5/24 16:48
     * @Descrintion 反馈接口json
     */
    public static Map response(String url, Object param) {
        if (url == null || "".equals(url)) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> stringHttpEntity = new HttpEntity<>(param.toString(), headers);
        Map response = restTemplate.postForObject(url, stringHttpEntity, Map.class);
        return response;
    }

    public static void postObject(String url, Object request) {
        String result = restTemplate.postForObject(url, request, String.class);
        System.out.println(result);
    }

    public static Map getResponse(String url) {
        if (url == null || "".equals(url)) {
            return null;
        }
        Map response = restTemplate.getForObject(url, Map.class);
        return response;
    }
}
